const fs = require('fs')

import { ObjectId, MongoClient } from 'mongodb'
import YAML from 'yamljs'

import BaseResult from '../lib/BaseResult'

const { mongo } = YAML.parse(fs.readFileSync('./server/config.yaml').toString());
const url = mongo.host;


class CategoryController {
    static async saveCategory(ctx) {
        let data = ctx.request.body;

        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("blog");
                if (data._id) {
                    let whereStr = { _id: ObjectId(data._id) };
                    dbo.collection("category").updateOne(whereStr, {
                        $set: {
                            title: data.title
                        }
                    }, function(err, res) {
                        if (err) throw err;
                        // console.log("文档更新成功");
                        ctx.body = new BaseResult(0, 0, data);
                        resolve();
                        db.close();
                    });
                } else {
                    // data.appKey = uuid.v1();
                    dbo.collection("category").insertOne(data, function(err, res) {
                        if (err) throw err;
                        // console.log("文档插入成功");
                        // ctx.body = "文档插入成功";
                        ctx.body = new BaseResult(0, 0, data);
                        resolve();
                        db.close();
                    });
                }

            });
        })
    }
  static  async category(ctx) {
        let data = ctx.request.body;
        return new Promise((resolve) => {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                console.log('数据库已创建');
                var dbo = db.db("blog");
                // var myobj = { name: "菜鸟教程", url: "www.runoob" };
                dbo.collection("category").find({}).toArray(function(err, res) {
                    if (err) throw err;
                    //console.log("文档插入成功");
                    //ctx.body = res;
                    ctx.body = new BaseResult(0, 0, res);
                    resolve();
                    db.close();
                });
            });
        })
    }
}
export default  CategoryController;